package com.apps.ftapp.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;

import com.apps.ftapp.MainActivity;
import com.apps.ftapp.R;
import com.apps.ftapp.model.ComModel;
import com.apps.ftapp.model.FaceModel;
import com.apps.ftapp.model.UserInfoModel;
import com.apps.ftapp.ui.MyProgressDialog;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.BroadCastManager;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.ImageDispose;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.PictureCutUtil;
import com.apps.ftapp.util.SharedPreferencesUtil;
import com.apps.ftapp.util.Tools;
import com.apps.ftapp.view.SuperEditText;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import de.hdodenhof.circleimageview.CircleImageView;
import es.dmoral.toasty.Toasty;


/**
 * 用户信息
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.userIcon)
    CircleImageView userIcon;
    @BindView(R.id.nickname)
    SuperEditText nickname;
    @BindView(R.id.account)
    TextView account;
    @BindView(R.id.company)
    TextView company;

    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.password)
    TextView password;
    @BindView(R.id.exit)
    Button exit;

    @BindView(R.id.exam_lin)
    LinearLayout exam_lin;
    @BindView(R.id.address_lin)
    LinearLayout address_lin;
    @BindView(R.id.password_lin)
    LinearLayout password_lin;
    @BindView(R.id.lin_main)
    LinearLayout lin;
    @BindView(R.id.face_rel)
    RelativeLayout face_rel;


    @BindView(R.id.cover)
    View cover;

    private LocalReceiver mReceiver;

    private Gson gson = new Gson();


    private String icon;

    public final static int REQUEST_CODE_CHOOSE = 2;

    private String yiji_name;


    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;


    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;
    private PopupWindow popupWindow;
    private View view;
    //下面这些变量是与题目有关的
    private File photoFile;  //存放图片文件，最后是上传这个file
    private CircleImageView civInformation;  //头像控件
    protected MyProgressDialog loadingDialog;  //上传如果延迟的话，会显示一个不停转圈的dialog
    private PictureCutUtil pictureCutUtil;   //图片压缩工具
    private String filename = System.currentTimeMillis() + ".png"; //如果拍照的话会存放在一个临时文件，所以文件名也是随时生成，以免混淆
    public final static int CONSULT_DOC_PICTURE = 1000;  //相册
    public final static int CONSULT_DOC_CAMERA = 1001;  //拍照
    public final static int CONSULT_DOC_CUTTING = 1002;  //裁剪
    private Uri outputFileUri;  //拍照获得的图片的uri
    private Bitmap detailBitmap;


    private String strname;

    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播后的处理

            shuaxin();

        }

    }


    public void shuaxin() {
        yiji_name = SharedPreferencesUtil.getData(getApplicationContext(), "yijiName", "") + "";
        L.i("main", "yiji_--------UserInfoActivity------name>>>>" + yiji_name);
        if (!"".equals(Tools.isNull(yiji_name))) {
            company.setText(Tools.isNull(yiji_name));
        } else {
            company.setText("教师招聘");
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        //接收广播
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("UserInfoActvitiy");
            mReceiver = new LocalReceiver();
            BroadCastManager.getInstance().registerReceiver(this,
                    mReceiver, filter);//注册广播接收者
        } catch (Exception e) {
            e.printStackTrace();
        }
        loadData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);

        setTitle("用户信息");
        loadingDialog = MyProgressDialog.createDialog(this);
        loadingDialog.setCanceledOnTouchOutside(false);

        //显示图片的配置  
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
        loadData();

        exit.setOnClickListener(this);
        address_lin.setOnClickListener(this);
        userIcon.setOnClickListener(this);
        exam_lin.setOnClickListener(this);
        password_lin.setOnClickListener(this);
        yiji_name = SharedPreferencesUtil.getData(getApplicationContext(), "yijiName", "") + "";
        company.setText(yiji_name);
        face_rel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow();
            }
        });
        cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                cover.setVisibility(View.GONE);
            }
        });
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!nickname.getText().toString().trim().equals("")) {
                    saveinfo();
                } else {
                    Toasty.normal(getApplicationContext(), "请填写昵称").show();

                }

            }
        });
        initPhotoOptions();
        nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(UserInfoActivity.this, NickNameActivity.class);

                if (strname.length() >= 18) {
                    strname = strname.substring(0, 18);// 取得字符串数据的前8位
                }
                intent.putExtra("nickname", strname);
                startActivity(intent);
            }
        });

    }


    private void loadData() {

        
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("settings/", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));

                    UserInfoModel result = gson.fromJson(new String(responseBody), UserInfoModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {
                        imageLoader.displayImage(result.getData().getLargeAvatar(), userIcon, options);
                        nickname.setText(result.getData().getNickname());
                        strname = result.getData().getNickname();
                        account.setText(result.getData().getVerifiedMobile());


                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });


    }

    private void saveinfo() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("nickname", nickname.getText().toString().trim());
        Async.post("settings/nickname", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    ComModel result = gson.fromJson(new String(responseBody), ComModel.class);
                    if (result.getSuccess() == 1) {
                        Toasty.normal(getApplicationContext(), "昵称修改成功！").show();
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });


    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.exit:

                tuichu();

                break;

            case R.id.address_lin:

                ActivitySkipUtil.skipAnotherActivity(UserInfoActivity.this, UserAddressListActivity.class, false);

                break;


            case R.id.userIcon:
                //选择图片
//                PhotoPicker.builder()
//                        .setPhotoCount(1)
//                        .setShowCamera(true)
//                        .setShowGif(true)
//                        .setPreviewEnabled(false)
//                        .start(this, PhotoPicker.REQUEST_CODE);

//                Picker.from(this)
//                        .count(1)
//                        .enableCamera(true)
//                        .setEngine(new GlideEngine())
//                        .forResult(REQUEST_CODE_CHOOSE);


                break;

            case R.id.exam_lin:

                Constant.IS_EDIT_CHANAGE = "UserInfoActivity";
                ActivitySkipUtil.skipAnotherActivity(UserInfoActivity.this, SubjectMoreActivity.class, false);

                break;

            case R.id.password_lin:
                ActivitySkipUtil.skipAnotherActivity(UserInfoActivity.this, UpdPasswordActivity.class, false);

                break;
        }

    }

    private void tuichu() {

        SharedPreferencesUtil.remove(getApplicationContext(), "uid");
        SharedPreferencesUtil.remove(getApplicationContext(), "token");
        //  Log.i("MAIN",jsonBean.toString());
        SharedPreferencesUtil.putBoolean(UserInfoActivity.this, SharedPreferencesUtil.IS_LOGIN, true);
        ActivitySkipUtil.skipAnotherActivity(UserInfoActivity.this, LoginActivity.class, true);
        MainActivity.activity.finish();
    }

    private void initPhotoOptions() {
        view = LayoutInflater.from(this).inflate(R.layout.popup_window_camera_options_layout, null);
        TextView camera = (TextView) view.findViewById(R.id.popup_from_camera);
        TextView album = (TextView) view.findViewById(R.id.popup_from_album);
        TextView cancel = (TextView) view.findViewById(R.id.popup_cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(UserInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(UserInfoActivity.this, Manifest.permission.CAMERA)
                                != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(UserInfoActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(UserInfoActivity.this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE);

                } else {
                    File file = new File(Environment.getExternalStorageDirectory(), filename);
                    //File file = new File(Environment.getExternalStorageDirectory() + "/iweishi/cache");


                    //outputFileUri = Uri.fromFile(file);
                    outputFileUri = getUriForFile(UserInfoActivity.this, file);
                    Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                    startActivityForResult(intentPhoto, CONSULT_DOC_CAMERA);
                    overridePendingTransition(R.anim.popup_enter1, R.anim.popup_exit1);
                    popupWindow.dismiss();
                }
            }
        });
        album.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(UserInfoActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(UserInfoActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(UserInfoActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);

                } else {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "选择图片"), CONSULT_DOC_PICTURE);
                    overridePendingTransition(R.anim.popup_enter1, R.anim.popup_exit1);
                    popupWindow.dismiss();
                }

            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }


    private void showPopupWindow() {
        cover.setVisibility(View.VISIBLE);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.PopupAnimation2);
            popupWindow.setClippingEnabled(true);
            popupWindow.setFocusable(true);
            ColorDrawable cdw = new ColorDrawable(0x00000000);
            popupWindow.setBackgroundDrawable(cdw);
            popupWindow.setOutsideTouchable(true);
            popupWindow.update();
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    cover.setVisibility(View.GONE);
                }
            });
        }
        popupWindow.showAtLocation(lin, Gravity.BOTTOM, 0, 0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case CONSULT_DOC_PICTURE: //相册选择

                Uri photo = data.getData();  //图片已经存在，所以data中就是图片的uri
                try {
                    startPhotoZoom(data.getData());  //头像一般都要裁剪

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            case CONSULT_DOC_CAMERA:  //拍照
                if (outputFileUri != null) {
                    startPhotoZoom(outputFileUri);  //裁剪
                }
                break;

            case CONSULT_DOC_CUTTING:  //裁剪完之后，压缩保存并上传
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //裁剪之后的图片不能放回原地址，所以要存放在一个临时file中再上传
    private void setPicToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            // 取得SDCard图片路径做显示
            Bitmap photo = extras.getParcelable("data");
            //sharePreferenceUtil.setImg(photo); //我用sharePreference保存图片

//            photoFile = pictureCutUtil.cutPictureQuality(photo, "ff");  //压缩并保存
//            if (loadingDialog != null) {  //上传可能要延迟，先弹出等待框
//                loadingDialog.show();
//            }
//            detailBitmap.recycle();
//            detailBitmap = null;
//            detailBitmap = getZoomBitmap(photoFile.getPath());
            postIcon(photo); //上传
        }
    }

    private Bitmap getZoomBitmap(String path) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        int degree = ImageDispose.readPictureDegree(path);
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        opts.inJustDecodeBounds = false;
        float ww = 384f;
        float hh = 768f;
        int be = 1;
        if (width > ww && width > height) {
            be = (int) (width / ww);
        } else if (width <= height && height > hh) {
            be = (int) (height / hh);
        }
        if (be <= 1) {
            be = 1;
        }
        opts.inSampleSize = be;
        Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
        return ImageDispose.rotaingImageView(degree, bitmap);
    }

    private void postIcon(Bitmap bitmap) {
        loadingDialog.setMsg("正在上传...");
        loadingDialog.show();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
        RequestParams params = new RequestParams();
        params.add("userId", Constant.uid);
        params.add("token", Constant.token);
        params.put("avatar", inputStream, "bbb.jpg", "multipart/form-data");
        Async.post2("avatarapi", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    FaceModel result = gson.fromJson(new String(responseBody), FaceModel.class);
                    if (result.getSuccess().equals("1")) {
                        imageLoader.displayImage(result.getMediumAvatar(), userIcon, options);
                        loadingDialog.dismiss();
                        Toasty.normal(UserInfoActivity.this, "头像修改成功");
                    } else {
                        loadingDialog.dismiss();
                        Toasty.normal(getApplicationContext(), result.getError()).show();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }


    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CONSULT_DOC_CUTTING);  //返回去
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {


        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                File file = new File(Environment.getExternalStorageDirectory(), filename);
                //File file = new File(Environment.getExternalStorageDirectory() + "/iweishi/cache");


                //outputFileUri = Uri.fromFile(file);
                outputFileUri = getUriForFile(UserInfoActivity.this, file);
                Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                startActivityForResult(intentPhoto, CONSULT_DOC_CAMERA);
                overridePendingTransition(R.anim.popup_enter1, R.anim.popup_exit1);
                popupWindow.dismiss();
            } else {
                Toasty.normal(getApplicationContext(), "请打开权限").show();

            }
        }


        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "选择图片"), CONSULT_DOC_PICTURE);
                overridePendingTransition(R.anim.popup_enter1, R.anim.popup_exit1);
                popupWindow.dismiss();
            } else {

                Toasty.normal(getApplicationContext(), "请打开权限").show();
            }
        }


        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    public static Uri getUriForFile(Context context, File file) {
        return FileProvider.getUriForFile(context, "com.apps.ftapp.fileprovider", file);
    }


}
